package com.eh.message;

import com.eh.base.EndPoint;
import com.eh.model.User;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;
import org.apache.commons.lang.SerializationUtils;

import java.io.IOException;

/**
 * Created by David Li on 2016/5/17.
 */
public class MessageConsumerThread extends EndPoint implements Consumer, Runnable {

    public MessageConsumerThread(String endPointName) {
        super(endPointName);
    }

    @Override
    public void run() {
        try {
            //start consuming messages. Auto acknowledge messages.
            channel.basicConsume(endPointName, true, this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void handleConsumeOk(String s) {
        System.out.println("Consumer " + s + " registered");
    }

    @Override
    public void handleDelivery(String s, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
        User user = (User) SerializationUtils.deserialize(bytes);
        System.out.printf("Message Received: %n%s%n" , user);
    }

    @Override
    public void handleCancelOk(String s) {
    }

    @Override
    public void handleCancel(String s) throws IOException {
    }

    @Override
    public void handleShutdownSignal(String s, ShutdownSignalException e) {
    }

    @Override
    public void handleRecoverOk(String s) {
    }

}
